package 并发编程12.读写锁测试;

import java.util.HashMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author idea
 * @data 2019/1/28
 */
public class Cache {

    static HashMap<String,Object> map=new HashMap<String,Object>();

    static ReadWriteLock readWriteLock=new ReentrantReadWriteLock();

    static Lock readLock=readWriteLock.readLock();

    static Lock writeLock=readWriteLock.writeLock();


    public static Object getKey(String key){
        readLock.lock();
        try {
            return map.get(key);
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }finally {
            readLock.unlock();
        }
    }

    public static void putKey(String key,Object object){
        writeLock.lock();
        try {
             map.put(key,object);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            writeLock.unlock();
        }
    }

    public static void clear(){
        writeLock.lock();
        map.clear();
        writeLock.unlock();
    }

    public static void main(String[] args) {

    }
}
